<?php

class AdminProduct extends Admin{

	public $useDB = array("Product", "Category");

	public function index($page=1,$sortby="id",$sortdir="desc"){
		$page = (int)$page>0 ? (int)$page : 1;;

		$this->set("total",$this->dbProduct->count());
		$this->set("page",$page);
		$this->set("sortby",$sortby);
		$this->set("sortdir",$sortdir);
		$this->set("products", $this->dbProduct->find(array(
			"order" => "$sortby $sortdir",
			"offset" => $page
		)));

		$this->render("admin/product/index");
	}

	public function edit($id=nil){
		if($id>0){
			$this->set("data", $this->dbProduct->get($id));
		}
		$this->render("admin/product/edit");
	}

	public function save(){
		$message = "Izmene su sačuvane.";
		$class = "ok";
		$data = $_POST["data"];//_dump($data); die;
		$redirect_id = $data["id"];
		if(!$this->dbProduct->save(&$data)){
			$class = "error";
			$message = implode(" ", $this->dbProduct->errors); //"Izmene nisu sačuvane.";
			$data["category_ids"][$data["category_id"]] = "Kategorija";
			$this->set("data", $data);
			$this->flashSet($message,$class);
			$this->render("admin/product/edit");
		}else{
			$this->flashSet($message,$class);
			redirect("/admin_product/edit/".$data["id"]);
		}
	}

	public function upload_image($product_id){
		$file = $_FILES["image_new"];
		$product = $this->dbProduct->row(array("conditions"=>array("id"=>$product_id)));
		$status = false;
		$image = (Object)array();
		if(!$file["error"] && $product){
			$dir = DIR_IMAGE . "/products/$product_id/";
			if(!is_dir($dir)){
				mkdir($dir,0777);
			}
			if(move_uploaded_file($file["tmp_name"], $dir.$file["name"])){
				if($status = $this->dbProduct->addImage($product_id,$file["name"])){
					$image = $this->dbProduct->getImage($product_id,$file["name"]);
				}
			}
		}
		echo json_encode((Object)array("status"=>$status,"image"=>$image));
	}

	public function delete($id){
		if($id>0){
			if(!$this->dbProduct->delete($id)){
				$this->flashSet("Proizvod nije obrisan.", "error");
			}else{
				empty_dir(DIR_IMAGE . "/products/$id",array(),true);
			}
		}
		$this->flashSet("Proizvod je obrisan.", "ok");
		redirect();
	}
}